// Copyright 2013 Ronald Schlenker, www.technewlogic.de.
// 
// This file is part of Byond.
// 
// Byond is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
// 
// Byond is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with Byond.  If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Utils;
using Utils.Messaging;

namespace Byond.Frontend.ViewModels
{
	internal class LogViewModel
	{
		private readonly UiDispatcher _dispatcher;
		private readonly LogMessageCache _cache;

		private readonly ObservableCollection<string> _logs = new ObservableCollection<string>();
		public IEnumerable<string> Logs { get { return _logs; } }

		public event MessageEventHandler SendMessage;

		private void Ctor()
		{
			foreach (var message in _cache.GetMessages())
				_logs.Add(message);

			_cache.NewLogMessages += Log;
		}

		private void Log(string message)
		{
			// Hier kann beim beenden eine ObjectDisposedException kommen
			try
			{
				_dispatcher.BeginInvokeIfInitialized(() =>
				{
					_logs.Insert(0, message);
					if (_logs.Count > 500)
						_logs.RemoveAt(_logs.Count - 1);
				});
			}
			catch (ObjectDisposedException)
			{
			}
		}

		public void GotoCode()
		{
			SendMessage(new ShowViewRequest(typeof(CodeEditorViewModel)));
		}

		public void ClearLog()
		{
			_logs.Clear();
		}
	}
}